using CoreManager.API.Common;
using CoreManager.Models.DTOs;
using CoreManager.Services.System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace CoreManager.API.System.Controllers
{
    /// <summary>
    /// 系统监控控制器
    /// </summary>
    [ApiController]
    [Route("api/system/[controller]")]
    // [Authorize] // 临时移除认证要求用于测试
    public class SystemMonitorController : BaseController
    {
        private readonly ISystemMonitorService _systemMonitorService;
        private readonly ILogger<SystemMonitorController> _logger;

        public SystemMonitorController(
            ISystemMonitorService systemMonitorService,
            ILogger<SystemMonitorController> logger) : base(logger)
        {
            _systemMonitorService = systemMonitorService;
            _logger = logger;
        }

        /// <summary>
        /// 获取系统监控数据
        /// </summary>
        /// <returns>系统监控数据</returns>
        [HttpGet("overview")]
        public async Task<IActionResult> GetSystemOverview()
        {
            try
            {
                var data = await _systemMonitorService.GetSystemMonitorDataAsync();
                return Success(data, "获取系统监控数据成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取系统监控数据");
            }
        }

        /// <summary>
        /// 获取CPU信息
        /// </summary>
        /// <returns>CPU信息</returns>
        [HttpGet("cpu")]
        public async Task<IActionResult> GetCpuInfo()
        {
            try
            {
                var data = await _systemMonitorService.GetCpuInfoAsync();
                return Success(data, "获取CPU信息成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取CPU信息");
            }
        }

        /// <summary>
        /// 获取内存信息
        /// </summary>
        /// <returns>内存信息</returns>
        [HttpGet("memory")]
        public async Task<IActionResult> GetMemoryInfo()
        {
            try
            {
                var data = await _systemMonitorService.GetMemoryInfoAsync();
                return Success(data, "获取内存信息成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取内存信息");
            }
        }

        /// <summary>
        /// 获取磁盘信息
        /// </summary>
        /// <returns>磁盘信息</returns>
        [HttpGet("disk")]
        public async Task<IActionResult> GetDiskInfo()
        {
            try
            {
                var data = await _systemMonitorService.GetDiskInfoAsync();
                return Success(data, "获取磁盘信息成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取磁盘信息");
            }
        }

        /// <summary>
        /// 获取网络信息
        /// </summary>
        /// <returns>网络信息</returns>
        [HttpGet("network")]
        public async Task<IActionResult> GetNetworkInfo()
        {
            try
            {
                var data = await _systemMonitorService.GetNetworkInfoAsync();
                return Success(data, "获取网络信息成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取网络信息");
            }
        }

        /// <summary>
        /// 获取操作系统信息
        /// </summary>
        /// <returns>操作系统信息</returns>
        [HttpGet("os")]
        public async Task<IActionResult> GetOperatingSystemInfo()
        {
            try
            {
                var data = await _systemMonitorService.GetOperatingSystemInfoAsync();
                return Success(data, "获取操作系统信息成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取操作系统信息");
            }
        }

        /// <summary>
        /// 获取进程列表
        /// </summary>
        /// <param name="top">获取前N个进程，默认20</param>
        /// <returns>进程列表</returns>
        [HttpGet("processes")]
        public async Task<IActionResult> GetProcessList([FromQuery] int top = 20)
        {
            try
            {
                if (top <= 0 || top > 100)
                {
                    return BadRequest("参数top必须在1-100之间");
                }

                var data = await _systemMonitorService.GetProcessListAsync(top);
                return Success(data, "获取进程列表成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取进程列表");
            }
        }

        /// <summary>
        /// 获取系统告警列表
        /// </summary>
        /// <returns>告警列表</returns>
        [HttpGet("alerts")]
        public async Task<IActionResult> GetSystemAlerts()
        {
            try
            {
                var data = await _systemMonitorService.GetSystemAlertsAsync();
                return Success(data, "获取系统告警成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取系统告警");
            }
        }

        /// <summary>
        /// 获取系统性能指标（实时数据）
        /// </summary>
        /// <returns>性能指标</returns>
        [HttpGet("metrics/realtime")]
        public async Task<IActionResult> GetRealtimeMetrics()
        {
            try
            {
                var systemData = await _systemMonitorService.GetSystemMonitorDataAsync();
                
                // 返回关键性能指标
                var metrics = new
                {
                    timestamp = DateTime.Now,
                    cpu = new
                    {
                        usage = systemData.Cpu.Usage,
                        temperature = systemData.Cpu.Temperature,
                        frequency = systemData.Cpu.Frequency
                    },
                    memory = new
                    {
                        usage = systemData.Memory.Usage,
                        used = systemData.Memory.Used,
                        available = systemData.Memory.Available
                    },
                    disk = new
                    {
                        usage = systemData.Disk.Usage,
                        readSpeed = systemData.Disk.ReadSpeed,
                        writeSpeed = systemData.Disk.WriteSpeed
                    },
                    network = new
                    {
                        latency = systemData.Network.Latency,
                        uploadSpeed = systemData.Network.UploadSpeed,
                        downloadSpeed = systemData.Network.DownloadSpeed,
                        packetsLost = systemData.Network.PacketsLost
                    }
                };

                return Success(metrics, "获取实时性能指标成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取实时性能指标");
            }
        }

        /// <summary>
        /// 获取系统健康状态
        /// </summary>
        /// <returns>系统健康状态</returns>
        [HttpGet("health")]
        public async Task<IActionResult> GetSystemHealth()
        {
            try
            {
                var systemData = await _systemMonitorService.GetSystemMonitorDataAsync();
                var alerts = await _systemMonitorService.GetSystemAlertsAsync();

                // 计算系统健康评分
                var healthScore = CalculateHealthScore(systemData);
                var status = GetHealthStatus(healthScore);

                var health = new
                {
                    score = healthScore,
                    status = status,
                    timestamp = DateTime.Now,
                    alerts = alerts.Where(a => !a.Resolved).Count(),
                    uptime = systemData.System.Uptime,
                    components = new
                    {
                        cpu = GetComponentHealth(systemData.Cpu.Usage),
                        memory = GetComponentHealth(systemData.Memory.Usage),
                        disk = GetComponentHealth(systemData.Disk.Usage),
                        network = systemData.Network.Latency < 100 ? "healthy" : "warning"
                    }
                };

                return Success(health, "获取系统健康状态成功");
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取系统健康状态");
            }
        }

        #region 私有方法

        /// <summary>
        /// 计算系统健康评分
        /// </summary>
        /// <param name="systemData">系统数据</param>
        /// <returns>健康评分 (0-100)</returns>
        private int CalculateHealthScore(SystemMonitorDto systemData)
        {
            var cpuScore = Math.Max(0, 100 - (int)systemData.Cpu.Usage);
            var memoryScore = Math.Max(0, 100 - (int)systemData.Memory.Usage);
            var diskScore = Math.Max(0, 100 - (int)systemData.Disk.Usage);
            var networkScore = systemData.Network.Latency < 50 ? 100 : 
                              systemData.Network.Latency < 100 ? 80 : 60;

            return (cpuScore + memoryScore + diskScore + networkScore) / 4;
        }

        /// <summary>
        /// 获取健康状态描述
        /// </summary>
        /// <param name="score">健康评分</param>
        /// <returns>状态描述</returns>
        private string GetHealthStatus(int score)
        {
            return score switch
            {
                >= 80 => "excellent",
                >= 60 => "good",
                >= 40 => "warning",
                _ => "critical"
            };
        }

        /// <summary>
        /// 获取组件健康状态
        /// </summary>
        /// <param name="usage">使用率</param>
        /// <returns>健康状态</returns>
        private string GetComponentHealth(double usage)
        {
            return usage switch
            {
                < 50 => "healthy",
                < 80 => "warning",
                _ => "critical"
            };
        }

        #endregion
    }
}
